package com.hd.sup.modules.vehicle.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hd.common.constant.BizConstant;
import com.hd.common.utils.StrUtils;
import com.hd.sup.core.rest.client.TransRestClient;
import com.hd.sup.core.rest.dto.TData;
import com.hd.sup.core.rest.dto.TransDataDto;
import com.hd.sup.modules.alarm.service.IAlarmDetailService;
import com.hd.sup.modules.enterprise.service.IEnterpriseService;
import com.hd.sup.modules.vehicle.mapper.VehicleEndPosMapper;
import com.hd.sup.modules.vehicle.model.VehicleEndPos;
import com.hd.sup.modules.vehicle.service.IVehicleEndPosService;
import com.hd.sup.modules.vehicle.service.IVehicleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 车辆末次信息表 | 看看pg有没有内存表 服务实现类
 * </p>
 *
 * @author chentl123
 * @since 2020-12-28
 */
@Slf4j
@Service
public class VehicleEndPosServiceImpl extends ServiceImpl<VehicleEndPosMapper, VehicleEndPos> implements IVehicleEndPosService {

    @Resource
    private IVehicleService vehicleService;

    @Resource
    private IEnterpriseService enterpriseService;

    @Resource
    private VehicleEndPosMapper vehicleEndPosMapper;

    @Resource
    private IAlarmDetailService alarmDetailService;

    @Resource
    private TransRestClient transRestClient;


    @Override
    public List<Map<String, Object>> getVehicleEndPosPage(Page<Map<String, Object>> page, VehicleEndPos vehicleEndPos) {
        return this.baseMapper.getVehicleEndPosPage(page, vehicleEndPos);
    }

    @Override
    public List<Map<String, Object>> getVehicleGps(VehicleEndPos param) {
        return this.baseMapper.getVehicleGps(param);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void refreshVehicleEndPos(VehicleEndPos veDto) {
        this.baseMapper.refreshVehicleEndPos(veDto);
    }

    @Override
    public List<VehicleEndPos> getUnCompletionVehicle() {
        return this.baseMapper.getUnCompletionVehicle();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void syncUnCompletionData(VehicleEndPos data) {


        String platNo = StrUtils.regexSpecialChar(data.getPlatNo());
        String platColor = data.getPlatNoColor();
        String deptId = data.getDeptId();

        // 1 调用接口获取车辆数据
        String vehicleInfo = transRestClient.getVehicleIdInfo(platNo);
        if (StringUtils.isBlank(vehicleInfo)) {
            log.error("[supervise] 联控平台车辆静态数据接口中返回结果为空");
            return;
        }

        TransDataDto v_td = JSONObject.parseObject(JSON.parse(vehicleInfo).toString(), TransDataDto.class);

        // 2 获取车辆数据后 调用企业接口或取企业数据
        List<TData> vDto = JSONObject.parseArray(v_td.getDataStr(), TData.class);

        //valid 1 车辆数据不存在
        if (CollectionUtils.isEmpty(vDto)) {
            log.warn("[supervise] 联控平台接口中返回 车辆数据 不存在");
            return;
        }

        TData v = vDto.get(0);

        //valid 2 车辆数据不合法
        if (StringUtils.isAnyEmpty(v.getOwnername(), v.getMcert())) {
            log.warn("[supervise] 联控平台接口中返回 车辆数据中 owner_name 或 m_cert 为空");
            //标记为同步异常
            updateStatus(platNo, platColor, BizConstant.StaticDataStatus.SYNC_FAILED.key(), "联控平台接口中返回 车辆数据中 owner_name 或 m_cert 为空");
            return;
        }


        String on = v.getOwnername();
        String mc = StrUtils.regexStr(v.getMcert(), "[^0-9]");
        String enterpriseInfo = transRestClient.getPermission(on, mc);

        //valid 1 企业数据不存在
        if (StringUtils.isBlank(enterpriseInfo)) {
            log.error("[supervise] 联控平台企业静态数据接口中返回结果为空");
            return;
        }
        TransDataDto e_td = JSONObject.parseObject(JSON.parse(enterpriseInfo).toString(), TransDataDto.class);
        List<TData> eDto = JSONObject.parseArray(e_td.getDataStr(), TData.class);

        //valid 2 企业数据为空
        if (CollectionUtils.isEmpty(eDto)) {
            log.warn("[supervise] 联控平台接口中返回 企业数据中  id_owner 或 owner_name 为空");
            //标记为同步异常
            updateStatus(platNo, platColor, BizConstant.StaticDataStatus.SYNC_FAILED.key(), "联控平台接口中返回 企业数据中  id_owner 或 owner_name 为空");
            return;
        }

        TData e = eDto.get(0);
        //设置企业区域编码
        e.setOrigziparea(StrUtils.cutSuffixZero(v.getOrigziparea()));
        e.setDeptId(deptId);

        //valid 2 企业名称或编号为空 则不插入
        if (StringUtils.isAnyEmpty(e.getId_owner(), e.getOwnername())) {
            log.warn("[supervise] 联控平台接口中返回 企业数据中  id_owner 或 owner_name 为空");
            //标记为同步异常
            updateStatus(platNo, platColor, BizConstant.StaticDataStatus.SYNC_FAILED.key(), "联控平台接口中返回 企业数据中  id_owner 或 owner_name 为空");
            return;
        }

        // 3 入库企业信息和车辆信息
        enterpriseService.generateEnterprise(e);

        //4 入库车辆
        vDto.stream().peek(one -> {
            one.setVclidcolor(platColor);
            one.setDeptId(deptId);
        }).collect(Collectors.toList());
        vehicleService.generateVehicle(vDto, e.getId_owner(), e.getOwnername());

    }

    @Override
    public void updateStatus(String platNo, String platColor, Integer staticDataStatus, String syncRemark) {
        LambdaUpdateChainWrapper<VehicleEndPos> update = new LambdaUpdateChainWrapper<>(vehicleEndPosMapper);
        update.eq(VehicleEndPos::getPlatNo, platNo)
                .eq(VehicleEndPos::getPlatNoColor, platColor)
                .set(VehicleEndPos::getSyncRemark, syncRemark)
                .set(VehicleEndPos::getStaticDataStatus, staticDataStatus)
                .update();
    }
}
